package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.AddressBookMapper;
import com.itheima.pojo.AddressBook;
import com.itheima.pojo.Code;
import com.itheima.pojo.Result;
import com.itheima.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook>implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 收货地址添加
     * @param addressBook
     * @return
     */
    @Override
    public Result add(@RequestBody AddressBook addressBook) {
        //直接添加
        addressBookMapper.insert(addressBook);
        return new Result(Code.OK,addressBook,"{}");
    }


    /**
     * 获取收货地址列表
     * @return
     */
    @Override
    public Result getlist() {
        List<AddressBook> list = addressBookMapper.selectList(null);
        return new Result(Code.OK,list,"{}");
    }


    /**
     * 修改收货地址
     * @param addressBook
     * @return
     */
    @Override
    public Result put(AddressBook addressBook) {
        //更新收货地址
        addressBookMapper.updateById(addressBook);
        return new Result(Code.OK, "修改成功", "{}");
    }

    /**
     * 根据id获取收货地址
     * @param id
     * @return
     */
    @Override
    public Result chaeckById(String id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return new Result(Code.OK,addressBook,"{}");
    }


    /**
     * 设置默认收货地址
     */
    @Override
    public Result setUpDefault(AddressBook addressBook) {
        //修改默认值设置值为0
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.set("is_default",0);
        wrapper.eq("is_default", 1);
        update(wrapper);

        UpdateWrapper wrapper1 = new UpdateWrapper();
        wrapper1.set("is_default", 1);
        wrapper1.eq("id", addressBook.getId());
        boolean update = update(wrapper1);
        if (update){
            return new Result(Code.OK,null,"{}");
        }
    return new Result(Code.ERR401,"","{}");

    }



    /**
     * 获取默认地址
     */
    @Override
    public Result getDefault() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("is_default", 1);
        AddressBook one = this.getOne(wrapper);
        if (one!=null){
            return new Result(Code.OK,one,"{}");
        }
        return new Result(Code.ERR401, null, "{}");
    }


    /**
     * 删除收货地址
     * @param ids
     * @return
     */
    @Override
    public Result delect(String ids) {
       addressBookMapper.deleteById(ids);

        return new Result(Code.OK, "删除成功", "{}");
    }
}
